package data_service

import (
	"errors"
	"time"

	"gitee.com/gldmmhh/bbs/data_access"
)

func GetPosts(page, limit int, sort, order string) (posts []data_access.Post, total int64, err error) {
	return data_access.GetPosts(page, limit, sort, order)
}

func GetPostDetail(postId, userId int64) (post *data_access.Post, isLiked, isSaved bool, err error) {
	post, err = data_access.GetPostById(postId)
	if err != nil {
		return nil, false, false, err
	}
	isLiked, err = data_access.IsPostLiked(postId, userId)
	if err != nil {
		return nil, false, false, err
	}
	isSaved, err = data_access.IsPostSaved(postId, userId)
	if err != nil {
		return nil, false, false, err
	}
	return post, isLiked, isSaved, nil
}

func LikePost(postId, likerId int64) error {
	isLiked, err := data_access.IsPostLiked(postId, likerId)
	if err != nil {
		return err
	}
	if isLiked {
		return errors.New("already liked")
	}
	return data_access.LikePost(postId, likerId)
}

func UnlikePost(postId, likerId int64) error {
	return data_access.UnlikePost(postId, likerId)
}

func SavePost(postId, saverId int64) error {
	isSaved, err := data_access.IsPostSaved(postId, saverId)
	if err != nil {
		return err
	}
	if isSaved {
		return errors.New("already saved")
	}
	return data_access.SavePost(postId, saverId)
}

func UnsavePost(postId, saverId int64) error {
	return data_access.UnsavePost(postId, saverId)
}

func CreatePost(writerId int64, summary, content string) (int64, error) {
	if summary == "" {
		//  summary = ai.GenerateSummary(content) // AI aummary generation
		summary = "AI Generated Summary"
	}
	post := data_access.Post{
		Writer:     writerId,
		Summary:    summary,
		Content:    content,
		UpdateTime: time.Now(),
	}
	return data_access.CreatePost(&post)
}

func UpdatePost(postId int64, summary, content string) error {
	post, err := data_access.GetPostById(postId)
	if err != nil {
		return err
	}
	if summary != "" {
		post.Summary = summary
	}
	if content != "" {
		post.Content = content
	}
	post.UpdateTime = time.Now()
	return data_access.UpdatePost(post)
}

func DeletePost(postId, userId int64) error {
	post, err := data_access.GetPostById(postId)
	if err != nil {
		return err
	}
	user, err := data_access.GetUserById(userId)
	if err != nil {
		return err
	}

	if post.Writer != userId && user.Type != 2 { // 2 is admin
		return errors.New("permission denied")
	}
	return data_access.DeletePost(postId)
}
